#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include <time.h>
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include "os_api.h"
#include "debug.h"
#include "dev_api.h"
#include "powerkey.h"


#define _STACK_SIZE	(1024*2)

static void* _task_stack = NULL;

static OSTaskRef _task_ref = NULL;
static OSFlagRef _flag_ref = NULL;

#define TASK_KEY_RELEASE    	0x01
#define TASK_KEY_SHORT_PRESS    0x02
#define TASK_KEY_LONG_PRESS		0x04


void _flag_set(int type)
{
    OSAFlagSet(_flag_ref, type, OSA_FLAG_OR);
}

void powerKeyPressCb(UINT8 status)
{
	static int powerKeyPressCount = 0;
	static int shortPressFlag = 0;
	static int longPressFlag = 0;
	
	if (status){	
		powerKeyPressCount++;
	}else{
		if (powerKeyPressCount >= 1){			
			// 松开
			_flag_set(TASK_KEY_RELEASE);
			shortPressFlag = 0;
			longPressFlag = 0;
			LOG_PRINTF("_task: release! tatus %d\n", status);
		}
		powerKeyPressCount = 0;
	}
	
	if (powerKeyPressCount >= 1 && !shortPressFlag){
		
		//短按
		_flag_set(TASK_KEY_SHORT_PRESS);
		shortPressFlag = 1;
		LOG_PRINTF("_task: shortPress! status %d\n", status);
	}

	if (powerKeyPressCount >= 50 && !longPressFlag){
		
		//长按
		_flag_set(TASK_KEY_LONG_PRESS);
		LOG_PRINTF("_task: longPress! status %d\n", status);
		longPressFlag = 1;
	}
}


void _task(void *ptr)
{
    OSA_STATUS status;
    UINT32 flag_value;
    UINT32 flag_mask = TASK_KEY_RELEASE|TASK_KEY_SHORT_PRESS|TASK_KEY_LONG_PRESS;

	// 注册powerkey的回调函数后，powerkey不再具备关机功能，需要客户自行处理
	hal_RegisterPowerkeyCB(powerKeyPressCb, 50);	

    while(1) {
        status = OSAFlagWait(_flag_ref, flag_mask, OSA_FLAG_OR_CLEAR, &flag_value, OSA_SUSPEND);
		ASSERT(status == OS_SUCCESS);
        if (flag_value & TASK_KEY_RELEASE) {
			LOG_PRINTF("_task: TASK_KEY_RELEASE\n");
        } else if (flag_value & TASK_KEY_SHORT_PRESS) {
			LOG_PRINTF("_task: TASK_KEY_SHORT_PRESS\n");
        } else if (flag_value & TASK_KEY_LONG_PRESS) {
			LOG_PRINTF("_task: TASK_KEY_LONG_PRESS\n");
			dev_CtrlPoweroff(1);
        }
    }
}

int main(void)
{
    int ret;
	
    ret = OSAFlagCreate(&_flag_ref);
    ASSERT(ret == OS_SUCCESS);

	_task_stack = malloc(_STACK_SIZE);
	ASSERT(_task_stack != NULL);

    ret = OSATaskCreate(&_task_ref, _task_stack, _STACK_SIZE, 120, "test-task", _task, NULL);
    ASSERT(ret == OS_SUCCESS);

	return 0;
}
